<template>
  <div class="demo-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>仓库管理</el-breadcrumb-item>
      <el-breadcrumb-item>库区</el-breadcrumb-item>
    </el-breadcrumb>
    <br>

    <!-- 条件查询区域 -->
    <el-card class="card search-card" shadow="hover">
      <el-form :model="searchForm" :inline="true" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="searchForm.SName" placeholder="请输入名称" clearable style="width: 200px" />
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="searchForm.Status" placeholder="请选择类型" clearable style="width: 200px">
            <el-option label="有效" value="1" />
            <el-option label="无效" value="0" />

          </el-select>
        </el-form-item>



        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作和内容区域 -->
    <el-card class="card content-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>数据列表</span>
          <div class="operation-buttons">
            <div class="operation-buttons">

              <el-button type="primary" style="margin-left: 16px" @click="drawer = true">新增</el-button>

            </div>
            <el-button type="success" @click="handleExport"><el-icon>
                <Download />
              </el-icon>导出</el-button>

          </div>
        </div>
      </template>

      <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange" border stripe
        style="width: 100%">
        <el-table-column type="selection" width="55" />
        <!-- <el-table-column prop="id" label="ID" width="80" />  -->
        <el-table-column prop="name" label="名称" min-width="120" />
        <el-table-column prop="contact_person" label="联系人" min-width="120" />
        <el-table-column prop="contact_phone" label="电话" min-width="120" />
        <el-table-column prop="address" label="地址" min-width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status == '1' ? 'success' : 'danger'">
              {{ row.status == '1' ? '有效' : '无效' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="180">
          <template v-slot="scoped">
            <el-tag>{{ moment(scoped.row.create_time).format("YYYY-MM-DD hh:mm:ss") }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetails(row)">
              <el-icon>
                <View />
              </el-icon>查看详情
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon>
                <Delete />
              </el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页区域 -->
    <el-card class="card pagination-card" shadow="hover">
      <div class="pagination-container">
        <div class="pagination-info">
          <span>共 {{ total }} 条记录，当前显示第 {{ (currentPage - 1) * pageSize + 1 }} - {{ Math.min(currentPage * pageSize,
            total)
          }} 条</span>
        </div>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>
  </div>



  <!-- 新增弹窗 -->

  <el-drawer v-model="drawer" title="商品新增" :with-header="false">
    <span>
      <h3>供应商新增</h3>
      <br>
      <el-form :model="form" label-width="auto" style="max-width: 600px">
        <el-form-item label="供应商名">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="form.contact_person" />
        </el-form-item>
        <el-form-item label="联系人手机号">
          <el-input v-model="form.contact_phone" />
        </el-form-item>
        <el-form-item label="供应商地址">
          <el-input v-model="form.address" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio value="1">有效</el-radio>
            <el-radio value="0">无效</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd"><el-icon>
              <Plus />
            </el-icon>新增</el-button>
        </el-form-item>
      </el-form>
    </span>
  </el-drawer>

  <!-- 供应商详情弹窗 -->
  <el-dialog v-model="detailsDialogVisible" title="供应商详情信息" :fullscreen="true" :before-close="handleCloseDetails"
    class="supplier-details-dialog">
    <div v-if="selectedSupplier" class="details-container">
      <!-- 顶部区域：供应商基本信息 -->
      <div class="supplier-info-section">
        <h3>供应商基本信息</h3>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="供应商名称">{{ selectedSupplier.name }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ selectedSupplier.contact_person }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedSupplier.contact_phone }}</el-descriptions-item>
          <el-descriptions-item label="地址">{{ selectedSupplier.address }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="selectedSupplier.status == '1' ? 'success' : 'danger'">
              {{ selectedSupplier.status == '1' ? '有效' : '无效' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ moment(selectedSupplier.create_time).format("YYYY-MM-DD hh:mm:ss")
          }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 底部区域：商品分配 -->
      <div class="products-section">
        <!-- 左侧：已分配商品 -->
        <div class="assigned-products">
          <div class="section-header">
            <h4>已分配商品</h4>
            <span class="count-badge">{{ assignedProducts.length }} 个商品</span>
          </div>
          <el-table :data="assignedProducts" border stripe style="width: 100%" height="400">
            <el-table-column prop="productName" label="商品名称" min-width="120" />
            <el-table-column prop="specification" label="规格型号" min-width="120" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="supplyPrice" label="供应价格" width="120">
              <template #default="{ row }">
                <span>¥{{ row.supplyPrice?.toFixed(2) || '0.00' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="isDefault" label="默认" width="80">
              <template #default="{ row }">
                <el-tag :type="row.isDefault == 1 ? 'success' : 'info'">
                  {{ row.isDefault == 1 ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button type="danger" size="small" @click="handleRemoveProduct(row)">
                  <el-icon>
                    <Delete />
                  </el-icon>移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 右侧：未分配商品 -->
        <div class="unassigned-products">
          <div class="section-header">
            <h4>未分配商品</h4>
            <div class="search-box">
              <el-input v-model="productSearchKeyword" placeholder="搜索商品" size="small" style="width: 200px" clearable>
                <template #prefix>
                  <el-icon>
                    <Search />
                  </el-icon>
                </template>
              </el-input>
            </div>
          </div>
          <el-table :data="filteredUnassignedProducts" border stripe style="width: 100%" height="400">
            <el-table-column prop="name" label="商品名称" min-width="120" />
            <el-table-column prop="specification" label="规格型号" min-width="120" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="category" label="商品分类" min-width="120" />
            <el-table-column prop="status" label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="row.status == 1 ? 'success' : 'danger'">
                  {{ row.status == 1 ? '上架' : '下架' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleAssignProduct(row)">
                  <el-icon>
                    <Plus />
                  </el-icon>分配
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="detailsDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleSaveAssignments">保存分配</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Download, View, Search } from '@element-plus/icons-vue'
import http from '@/Axios/Htttp';
import moment from 'moment';

// 搜索表单数据
const searchForm = reactive({ SName: '', Status: '', status: '', dateRange: [] })

// 定义表格数据类型
interface TableItem {
  id: number;
  name: string;
  type: string;
  status: string;
  createTime: string;
  description: string;
}

// 表格数据 - 添加正确的类型声明
const tableData = ref<TableItem[]>([]);
const loading = ref(false);
const selectedRows = ref<TableItem[]>([]);
const hasSelection = ref(false);

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const loadData = () => {
  loading.value = true // 添加加载状态

  http.get("api/SuppersProduct/GetSupperProduct", {
    params: {
      SName: searchForm.SName,
      Status: searchForm.Status,
      PageIndex: currentPage.value,
      PageSize: pageSize.value,
      PageCount: null,
      _t: new Date().getTime() // 添加时间戳防止缓存
    },
    cache: false // 禁用缓存
  }).then(res => {
    tableData.value = res.data.pageData
    total.value = res.data.todalCount
  }).catch(error => {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败，请检查网络连接')
  }).finally(() => {
    loading.value = false // 结束加载状态
  })
}


const form = reactive({
  "id": 0,
  "name": "",
  "contact_person": "",
  "contact_phone": "",
  "address": "",
  "status": 0,
  "create_time": new Date().toISOString()
})


// 工具函数
const getTypeTagType = (type: string): string => ({ type1: 'primary', type2: 'success', type3: 'warning' }[type] || 'info')
const getTypeLabel = (type: string): string => ({ type1: '类型一', type2: '类型二', type3: '类型三' }[type] || '未知')


const drawer = ref(false)

// 详情弹窗相关数据
const detailsDialogVisible = ref(false)
const selectedSupplier = ref<any>(null)
const assignedProducts = ref<any[]>([])
const unassignedProducts = ref<any[]>([]) // 新增：未分配商品列表
const productSearchKeyword = ref('') // 新增：用于搜索未分配商品

// 事件处理
const handleSearch = () => { currentPage.value = 1; loadData() }
const handleReset = () => {
  Object.assign(searchForm, { SName: '', Status: '', dateRange: [] });
  handleSearch()
}

// 查看详情
const handleViewDetails = (row: any) => {
  selectedSupplier.value = row
  detailsDialogVisible.value = true
  // 加载该供应商的商品分配数据
  loadAssignedProducts(row.id)
  // 加载未分配的商品
  loadUnassignedProducts(row.id)
}

// 关闭详情弹窗
const handleCloseDetails = () => {
  detailsDialogVisible.value = false
  selectedSupplier.value = null
  assignedProducts.value = []
  unassignedProducts.value = [] // 重置未分配商品列表
  productSearchKeyword.value = '' // 重置搜索关键词
}

// 加载已分配的商品
const loadAssignedProducts = (supplierId: number) => {
  http.get("api/SupplierProduct/GetSupplierProducts", {
    params: {
      SupplierId: supplierId,
      PageIndex: 1,
      PageSize: 100
    },
    cache: false
  }).then(res => {
    if (res.data.code == 200) {
      assignedProducts.value = res.data.pageData || []
    }
  }).catch(error => {
    console.error('加载供应商商品失败:', error)
    ElMessage.error('加载供应商商品失败')
  })
}

// 加载未分配的商品
const loadUnassignedProducts = (supplierId: number) => {
  http.get("api/SupplierProduct/GetAvailableProducts", {
    params: { supplierId },
    cache: false
  }).then(res => {
    if (res.data.code == 200) {
      unassignedProducts.value = res.data.result || []
    }
  }).catch(error => {
    console.error('加载未分配商品失败:', error)
    ElMessage.error('加载未分配商品失败')
  })
}

// 分配商品
const handleAddProduct = () => {
  ElMessage.info('分配商品功能待实现')
}

// 移除商品
const handleRemoveProduct = (product: any) => {
  ElMessageBox.confirm(`确定要移除商品"${product.productName}"吗？`, '确认移除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 调用移除API
    http.delete("api/SupplierProduct/RemoveProductFromSupplier", {
      params: {
        id: product.id
      }
    }).then(res => {
      if (res.data.code === 200) {
        ElMessage.success('移除成功')
        // 重新加载已分配商品列表
        loadAssignedProducts(selectedSupplier.value.id)
        // 重新加载未分配商品列表
        loadUnassignedProducts(selectedSupplier.value.id)
      } else {
        ElMessage.error(res.data.message || '移除失败')
      }
    }).catch(error => {
      console.error('移除商品失败:', error)
      ElMessage.error('移除失败，请检查网络连接')
    })
  }).catch(() => {
    // 用户取消移除
    ElMessage.info('已取消移除')
  })
}

// 保存分配
const handleSaveAssignments = () => {
  ElMessage.info('商品分配已实时保存，无需额外保存操作')
  detailsDialogVisible.value = false
}

// 搜索未分配商品
const filteredUnassignedProducts = computed(() => {
  if (!productSearchKeyword.value) {
    return unassignedProducts.value
  }
  return unassignedProducts.value.filter(product =>
    product.name.includes(productSearchKeyword.value) ||
    (product.specification && product.specification.includes(productSearchKeyword.value)) ||
    (product.category && product.category.includes(productSearchKeyword.value))
  )
})

// 分配商品
const handleAssignProduct = (product: any) => {
  // 创建价格输入对话框
  ElMessageBox.prompt(
    `请为商品"${product.name}"设置供应价格`,
    '设置价格',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^\d+(\.\d{1,2})?$/,
      inputErrorMessage: '请输入有效的价格（最多两位小数）',
      inputValue: product.supplyPrice || 0,
      inputType: 'number',
      inputPlaceholder: '请输入价格'
    }
  ).then(({ value }) => {
    const price = parseFloat(value);
    if (isNaN(price) || price < 0) {
      ElMessage.error('请输入有效的价格');
      return;
    }

    // 调用分配API
    const assignData = {
      supplierId: selectedSupplier.value.id,
      productId: product.id,
      supplyPrice: price, // 使用用户输入的价格
      isDefault: 0 // 默认非默认
    }

    http.post("api/SupplierProduct/AssignProductToSupplier", assignData).then(res => {
      if (res.data.code === 200) {
        ElMessage.success('分配成功')
        // 重新加载已分配商品列表
        loadAssignedProducts(selectedSupplier.value.id)
        // 重新加载未分配商品列表
        loadUnassignedProducts(selectedSupplier.value.id)
      } else {
        ElMessage.error(res.data.message || '分配失败')
      }
    }).catch(error => {
      console.error('分配商品失败:', error)
      ElMessage.error('分配失败，请检查网络连接')
    })
  }).catch(() => {
    // 用户取消分配
    ElMessage.info('已取消分配')
  })
}

// 价格变更处理
const handlePriceChange = (product: any) => {
  // 暂时禁用价格编辑功能，等待后端接口
  ElMessage.warning('价格编辑功能暂未开放，请联系管理员')
}

const handleAdd = () => {
  // 添加表单验证
  if (!form.name || !form.contact_person || !form.contact_phone || !form.address) {
    ElMessage.warning('请填写完整的供应商信息')
    return
  }

  loading.value = true

  http.post("api/SuppersProduct/AddSupplier", form).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.message)
      drawer.value = false
      // 重置表单
      Object.assign(form, {
        id: 0,
        name: "",
        contact_person: "",
        contact_phone: "",
        address: "",
        status: 0,
        create_time: new Date().toISOString() // 修复字段名
      })
      // 延迟刷新数据
      setTimeout(() => {
        loadData()
      }, 100)
    }
    else {
      ElMessage.error(res.data.message)
    }
  }).catch(error => {
    console.error('添加供应商失败:', error)
    ElMessage.error('添加供应商失败，请检查网络连接')
  }).finally(() => {
    loading.value = false
  })
}
const handleExport = () => ElMessage.success('导出功能')
const handleSelectionChange = (selection: any) => { selectedRows.value = selection; hasSelection.value = selection.length > 0 }
const handleSizeChange = (size: any) => { pageSize.value = size; currentPage.value = 1; loadData() }
const handleCurrentChange = (page: any) => { currentPage.value = page; loadData() }

// 编辑和删除操作
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除供应商"${row.name}"吗？`, '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 显示加载状态
    loading.value = true

    http.delete("api/SuppersProduct/DeleteSupplier", { params: { id: row.id } }).then(res => {
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        // 延迟刷新数据
        setTimeout(() => {
          loadData()
        }, 100)
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    }).catch(error => {
      console.error('删除供应商失败:', error)
      ElMessage.error('删除失败，请检查网络连接')
    }).finally(() => {
      loading.value = false
    })
  }).catch(() => {
    // 用户取消删除
    ElMessage.info('已取消删除')
  })
}


onMounted(loadData)
</script>

<style scoped>
/* 基础容器样式 */
.demo-container {
  padding: 20px;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 25%, #0f3460 50%, #1a1a2e 75%, #16213e 100%);
  background-image:
    radial-gradient(circle at 20% 80%, rgba(66, 165, 245, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(92, 107, 192, 0.1) 0%, transparent 50%);
  min-height: 100vh;
  position: relative;
}

/* 纹理背景 */
.demo-container::before {
  content: '';
  position: absolute;
  inset: 0;
  background-image:
    linear-gradient(rgba(255, 255, 255, 0.02) 1px, transparent 1px),
    linear-gradient(90deg, rgba(255, 255, 255, 0.02) 1px, transparent 1px);
  background-size: 20px 20px;
  pointer-events: none;
  z-index: 0;
}

.demo-container>* {
  position: relative;
  z-index: 1;
}

/* 卡片通用样式 */
.card {
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.92) !important;
  backdrop-filter: blur(15px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25);
}

/* 页头和操作区 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

/* 分页区域 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-card) {
  border-radius: 12px;
  transition: all 0.3s ease;
}

:deep(.el-card:hover) {
  transform: translateY(-2px);
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.3) !important;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid rgba(235, 238, 245, 0.5);
  background: rgba(248, 249, 250, 0.5);
  border-radius: 12px 12px 0 0;
}

:deep(.el-table) {
  margin-top: 10px;
  background: transparent;
}

:deep(.el-table__header-wrapper) {
  background: rgba(64, 158, 255, 0.1);
}

:deep(.el-table__body-wrapper) {
  background: transparent;
}

:deep(.el-breadcrumb__inner) {
  color: #2c3e50;
  font-weight: 500;
}

:deep(.el-breadcrumb__inner:hover) {
  color: #409EFF;
}

/* 详情弹窗样式 */
.supplier-details-dialog .el-dialog__header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  border-radius: 12px 12px 0 0;
  padding: 15px 20px;
}

.supplier-details-dialog .el-dialog__title {
  color: #303133;
  font-weight: 600;
}

.supplier-details-dialog .el-dialog__body {
  padding: 20px;
  background-color: #f5f7fa;
}

.supplier-details-dialog .el-dialog__footer {
  background-color: #f5f7fa;
  border-top: 1px solid #ebeef5;
  border-radius: 0 0 12px 12px;
  padding: 15px 20px;
}

.details-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow-y: auto;
  /* 允许内容滚动 */
}

.supplier-info-section {
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.supplier-info-section h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
  font-size: 18px;
}

.products-section {
  display: flex;
  gap: 20px;
  flex-grow: 1;
  /* 让两个区域平分剩余空间 */
}

.assigned-products,
.unassigned-products {
  flex: 1;
  /* 让两个区域平分剩余空间 */
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.count-badge {
  background-color: #409EFF;
  color: #fff;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: bold;
}

.search-box {
  display: flex;
  align-items: center;
}

.search-box .el-input {
  width: 200px;
}

.search-box .el-input__inner {
  border-radius: 20px;
  border-color: #dcdfe6;
  padding-left: 30px;
}

.search-box .el-input__prefix {
  left: 10px;
}

.search-box .el-input__suffix {
  right: 10px;
}
</style>
